package com.mrlv.api.utils.validator;

import com.alibaba.fastjson.JSON;

import com.google.common.collect.Maps;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 字段校验工具
 * @author Administrator
 */
public class ValidatorUtils {


    private static Validator validatorFast = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    private static Validator validatorAll = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();
    /**
     * 校验遇到第一个不合法的字段直接返回不合法字段，后续字段不再校验
     * @Time 2020年6月22日 上午11:36:13
     * @param domain
     * @param groups
     * @return
     * @throws Exception
     */
    public static <T> Map<Object, Object> validateFast(T domain, Class<?>... groups){
        Set<ConstraintViolation<T>> validateResult = validatorFast.validate(domain, groups);
        Map<Object, Object> map = Maps.newHashMap();
        if(validateResult.size() > 0) {
            map.put(validateResult.iterator().next().getPropertyPath(), validateResult.iterator().next().getMessage());
//            System.out.println(validateResult.iterator().next().getPropertyPath() +"："+ validateResult.iterator().next().getMessage());
        }
        return map;
    }

    /**
     * 校验所有字段并返回不合法字段
     * @Time 2020年6月22日 上午11:36:55
     * @param domain
     * @param groups
     * @return
     * @throws Exception
     */
    public static <T> Map<Object, Object> validateAll(T domain, Class<?> groups){
        Set<ConstraintViolation<T>> validateResult = validatorAll.validate(domain, groups);
        Map<Object, Object> map = Maps.newHashMap();
        if(validateResult.size() > 0) {
            Iterator<ConstraintViolation<T>> it = validateResult.iterator();
            while(it.hasNext()) {
                ConstraintViolation<T> cv = it.next();
                map.put(cv.getPropertyPath(), cv.getMessage());
//                System.out.println(cv.getPropertyPath()+"："+cv.getMessage());
            }
        }
        return map;
    }


    /**
     * 校验所有字段  不通过就抛异常
     * @Time 2020年6月22日 上午11:36:55
     * @param domain
     * @param groups
     * @return
     * @throws MasterException
     */
    public static  <T> void validate(T domain, Class<?> groups){
        Map map = ValidatorUtils.validateAll(domain, groups);
       if(map.size() != 0){
           throw new MasterException(ResultCode.INVALID_PARAM.getCode(), JSON.toJSON(map).toString());
       }
    }


}
